'''
Created on 17-05-2011

@author: Filon
'''
import re

'''
Creates regexp
'''   
def run(format, min = None, max = None):
    if min == None:
        min = "1970-01-01"
    if max == None:
        max = "2099-12-31"
    if is_valid_date(format, min, max) >= 0:
        return year(min, max)
    
    
'''
Function responsible for validating format and limits
'''
def is_valid_date(format, min, max):
    if format == "%Y-%m-%d":
        Y1 = min[0:4]
        M1 = min[5:7]
        D1 = min[8:10]
        
        Y2 = max[0:4]
        M2 = max[5:7]
        D2 = max[8:10]

        
        if int(Y1) < 1970 or int(Y1) > 2099 or int(Y2) < 1970 or int(Y2) > 2099:
            raise Exception('Bad year')
        if int(M1) < 0 or int(M1) > 12 or int(M2) < 0 or int(M2) > 12:
            raise Exception('Bad month')
        if  int(D1) < 0 or int(D1) > 31 or int(D2) < 0 or int(D2) > 31:
            raise Exception('Bad day')
        else:
            if int(Y1) == int(Y2) and int(M1) == int(M2):
                return 0
            elif int(Y1) == int(Y2) and int(M2) - int(M1) == 1:
                return 1
            elif int(Y1) == int(Y2):
                return 2
            elif int(Y2) - int(Y1) == 1:
                return 3
            else:
                return 4
    else:
        raise Exception('unsuported format. Try: %Y-%m-%d')

'''
Function responsible for creating regexp for all years
'''  
def year(min, max):    
    
    return r'((((19|20)(([02468][048])|([13579][26]))-02-29))|((20[0-9][0-9])|(19[0-9][0-9]))-((((0[1-9])|(1[0-2]))-((0[1-9])|(1\d)|(2[0-8])))|((((0[13578])|(1[02]))-31)|(((0[1,3-9])|(1[0-2]))-(29|30)))))'       

    
if __name__ == '__main__':
    xxx2 = run("%Y-%m-%d")
 
    print (xxx2)
    
    print(re.match(xxx2, "2000-02-29"))
